package cc.uncarbon.module.appapi.service;

import cc.uncarbon.framework.core.constant.HelioConstant;
import cc.uncarbon.framework.core.context.UserContextHolder;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.page.PageParam;
import cc.uncarbon.framework.core.page.PageResult;

import cc.uncarbon.module.appapi.mapper.BookCategoryMapper;
import cc.uncarbon.module.appapi.mapper.BookOrderMapper;

import cc.uncarbon.module.appapi.model.request.AdminBookOrderListDTO;
import cc.uncarbon.module.appapi.model.request.BookOrderInsertOrUpdateDTO;
import cc.uncarbon.module.appapi.model.response.BookCategoryBO;
import cc.uncarbon.module.appapi.model.response.BookOrderBO;
import cc.uncarbon.module.appapi.model.response.BookOrderCategoryBO;
import cc.uncarbon.module.appapi.model.vo.BookOrderByMonthVO;
import cc.uncarbon.module.appapi.model.vo.BookOrderVO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yanrumiao.entity.BookCategoryEntity;
import com.yanrumiao.entity.BookOrderEntity;
import com.yanrumiao.entity.OrdersEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.MonthDay;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 数据表注释
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class BookOrderService {

    private final BookOrderMapper bookOrderMapper;
    private final BookCategoryMapper bookCategoryMapper;

    public BookOrderVO appList(String yearAndMonth) {
        System.out.println(yearAndMonth+"------------------------------");
        LocalDate now = LocalDate.parse(yearAndMonth + "-01");
        BookOrderVO bookOrderVO = new BookOrderVO();
        QueryWrapper<BookOrderEntity> queryWrapper = new QueryWrapper<>();
        // 获取当前日期范围
//        LocalDate now = LocalDate.now();
        LocalDate firstDayOfMonth = now.withDayOfMonth(1);
        LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());

        queryWrapper.select("DATE(day) as date", "SUM(money) as count")
                .eq("user_id", UserContextHolder.getUserContext().getUserId())
                .ge("DATE(day)", firstDayOfMonth)
                .le("DATE(day)", lastDayOfMonth)
                .groupBy("DATE(day)")
                .orderByDesc("date");

        List<Map<String, Object>> maps = bookOrderMapper.selectMaps(queryWrapper);
        if(maps == null){
            return bookOrderVO;
        }
        List<BookOrderBO> list = new ArrayList<>(maps.size());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


        QueryWrapper<BookOrderEntity> queryWrapper1 = new QueryWrapper<>();

        queryWrapper1.select("SUM(money) as count")
                .eq("user_id", UserContextHolder.getUserContext().getUserId())
                .ge("DATE(day)", firstDayOfMonth)
                .le("DATE(day)", lastDayOfMonth);
        List<Map<String, Object>> selectMaps = bookOrderMapper.selectMaps(queryWrapper1);


        bookOrderVO.setDate(now.getYear() + "-" + now.getMonthValue());
//        bookOrderVO.setCount((BigDecimal) selectMaps.get(0).get("count"));
        if(selectMaps != null && !selectMaps.isEmpty()){
            Map<String, Object> resultMap = selectMaps.get(0);
            if(resultMap != null){
                bookOrderVO.setCount((BigDecimal) resultMap.get("count"));
            }else{
                bookOrderVO.setCount(new BigDecimal("0"));
            }
        }
        System.out.println(maps.toString() + "--------5555-------------------");
        if (maps != null && !maps.isEmpty()) {
            for (Map<String, Object> map : maps) {
                if (map != null && map.get("date") != null && map.get("count") != null) {
                    try {
                        BookOrderBO bookOrderBO = new BookOrderBO();
                        String date = map.get("date").toString();
                        LocalDate localDate = LocalDate.parse(date, formatter);
                        MonthDay monthDay = MonthDay.from(localDate);
                        String monthDayStr = monthDay.format(DateTimeFormatter.ofPattern("MM-dd"));
                        List<BookOrderCategoryBO> dayList = getOrderByDay(localDate);
                        bookOrderBO.setList(dayList);
                        bookOrderBO.setDate(localDate);
                        DateTimeFormatter chineseWeekFormatter = DateTimeFormatter.ofPattern("E", Locale.CHINESE);
                        String chineseWeek = localDate.format(chineseWeekFormatter);

                        bookOrderBO.setWeek(chineseWeek);
                        bookOrderBO.setCount((BigDecimal) map.get("count"));
                        bookOrderBO.setMonthDay(monthDayStr);

                        list.add(bookOrderBO);
                    } catch (Exception e) {
                        // 记录日志或适当处理解析异常
                        continue;
                    }
                }
            }
        }
        bookOrderVO.setList(list);

        return bookOrderVO;
    }

    private List<BookOrderCategoryBO> getOrderByDay(LocalDate localDate) {
        QueryWrapper<BookOrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATE(day)", localDate);
        queryWrapper.eq("user_id", UserContextHolder.getUserContext().getUserId());
        queryWrapper.orderByDesc("day");
        List<BookOrderEntity> entityList = bookOrderMapper.selectList(queryWrapper);

        List<BookOrderCategoryBO> list = new ArrayList<>();
        entityList.forEach(entity -> {
            BookOrderCategoryBO bookOrderCategoryBO = new BookOrderCategoryBO();
            bookOrderCategoryBO.setMoney(entity.getMoney());
            bookOrderCategoryBO.setOrderType(entity.getOrderType());
            BookCategoryEntity bookCategoryEntity = bookCategoryMapper.selectById(entity.getCategoryId());
            BookCategoryBO categoryBO = new BookCategoryBO();

            categoryBO.setIcon(bookCategoryEntity.getIcon());
            categoryBO.setName(bookCategoryEntity.getName());
            bookOrderCategoryBO.setCategory(categoryBO);
            list.add(bookOrderCategoryBO);
        });
        return list;
    }


    /**
     * APP端-新增订单
     */
    @Transactional(rollbackFor = Exception.class)
    public Long appInsert(BookOrderInsertOrUpdateDTO dto) {
        log.info("[APP端-数据表注释-新增] >> DTO={}", dto);

        // 清空ID，确保是新增操作
        dto.setId(null);

        // 创建实体对象并复制属性
        BookOrderEntity entity = new BookOrderEntity();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");

// 解析字符串为 LocalDate
        LocalDate date = LocalDate.parse(dto.getDay(), formatter);
        entity.setDay(date);
        BeanUtil.copyProperties(dto, entity);
        entity.setUserId(UserContextHolder.getUserContext().getUserId());

        // 执行插入操作
        bookOrderMapper.insert(entity);

        // 返回生成的ID
        return entity.getId();
    }


    public BookOrderByMonthVO getListByMonth() {
        QueryWrapper<BookOrderEntity> queryWrapper = new QueryWrapper<>();
        // 获取今年的第一天和最后一天
        LocalDate now = LocalDate.now();
        LocalDate firstDayOfYear = now.withDayOfYear(1);
        LocalDate lastDayOfYear = now.withDayOfYear(now.lengthOfYear());

        queryWrapper.select("MONTH(day) as month", "SUM(money) as total")
                .eq("user_id", UserContextHolder.getUserContext().getUserId())
                .ge("DATE(day)", firstDayOfYear)
                .le("DATE(day)", lastDayOfYear)
                .groupBy("MONTH(day)")
                .orderByAsc("month");
        List<Map<String, Object>> maps = bookOrderMapper.selectMaps(queryWrapper);
        if(maps == null){
            return new BookOrderByMonthVO();
        }
        List<String> list = new ArrayList<>(maps.size());
        List<BigDecimal> listCount = new ArrayList<>(maps.size());
        for (Map<String, Object> map : maps) {
            list.add(map.get("month").toString());
            listCount.add(new BigDecimal(map.get("total").toString()));
        }
        BookOrderByMonthVO bookOrderByMonthVO = new BookOrderByMonthVO();
        bookOrderByMonthVO.setTitle(list);
        bookOrderByMonthVO.setTotal(listCount);
        return bookOrderByMonthVO;
    }

    public BookOrderByMonthVO getListByCategory() {
        QueryWrapper<BookOrderEntity> queryWrapper = new QueryWrapper<>();
        // 获取今年的第一天和最后一天
        LocalDate now = LocalDate.now();
        LocalDate firstDayOfYear = now.withDayOfYear(1);
        LocalDate lastDayOfYear = now.withDayOfYear(now.lengthOfYear());
        BookOrderByMonthVO bookOrderByMonthVO = new BookOrderByMonthVO();
        queryWrapper.select("category_id", "MONTH(day) as month", "SUM(money) as total")
                .eq("user_id", UserContextHolder.getUserContext().getUserId())
                .ge("DATE(day)", firstDayOfYear)
                .le("DATE(day)", lastDayOfYear)
                .groupBy("category_id")
                .orderByAsc("month");
        List<Map<String, Object>> maps = bookOrderMapper.selectMaps(queryWrapper);
        if(maps == null){
            return bookOrderByMonthVO;
        }
        List<String> list = new ArrayList<>(maps.size());
        List<BigDecimal> listTotal = new ArrayList<>(maps.size());
        for (Map<String, Object> map : maps) {

            BookCategoryEntity category = bookCategoryMapper.selectById((Serializable) map.get("category_id"));
            if (category != null) {
                list.add(category.getName());
            }
            listTotal.add(new BigDecimal(map.get("total").toString()));
        }

        bookOrderByMonthVO.setTitle(list);
        bookOrderByMonthVO.setTotal(listTotal);
        return bookOrderByMonthVO;
    }
}
